import { IStorage } from './base';
import { Model } from 'sequelize-typescript';

export class MemoryStorage<T extends Model<T>> implements IStorage<T> {
    constructor(public prefix: string) { 
    }

    _store: {[index: string]: T} = {};
    async get(key: string): Promise<T> {
        key = this.getFullKey(key);
        return this._store[key];
    }

    async set(obj: T): Promise<any> {
        if (!obj)
            return;
        let key = this.getFullKey(obj.id);
        return this._store[key] = obj;
    }

    async remove(obj: T): Promise<any> {
        if (!obj) { 
            return;
        }
        let key = this.getFullKey(obj.id);
        delete this._store[key];
    }

    async removeAll(): Promise<any> {
        this._store = {};
    }

    private getFullKey(id: string) { 
        return `${this.prefix}:${id}`;
    }
}